package com.systemframework.valid;

import jodd.util.StringUtil;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.regex.Pattern;

import static java.lang.annotation.ElementType.*;

/**
 * @author summer
 * @Description: 不为空进行规则校验
 */
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NotBlankThenPattern.NotBlankThenPatternValidation.class)
@Documented
public @interface NotBlankThenPattern {

    String regexp() default "";

    String message() default "格式错误";


    Class<?>[] groups() default {};


    Class<? extends Payload>[] payload() default {};


    class NotBlankThenPatternValidation implements ConstraintValidator<NotBlankThenPattern, String> {

        private Pattern pattern;

        @Override
        public void initialize(NotBlankThenPattern constraintAnnotation) {
            this.pattern = Pattern.compile(constraintAnnotation.regexp());
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (StringUtil.isBlank(value)) {
                return true;
            }
            return pattern.matcher(value).matches();
        }
    }
}

